// index.js
const db = wx.cloud.database();
const util = require("../../utils/util");
import { login } from "../../utils/homeApi";
Page({
  data: {
    info: {
      longitude: "",
      latitude: "",
      polyline: [],
      points: [],
    },
    recordId: "", //用开始的时间,
    markers: [
      {
        iconPath: "../images/car.png",
        latitude: "",
        longitude: "",
        width: 16,
        height: 20,
        rotate: 0,
      },
    ],
  },

  onLoad() {
    var that = this;
    wx.getLocation({
      success: function (res) {
        that.data.info.longitude = res.longitude;
        that.data.info.latitude = res.latitude;
        that.setData({
          info: that.data.info,
        });
      },
    });
  },

  onShow: function () {
    wx.getSetting({
      success: (res) => {
        console.log("用户的设置是", res.authSetting);
        if (!res.authSetting["scope.userLocationBackground"]) {
          wx.showModal({
            title: "位置权限",
            content: "请打开后台获取位置权限",
            success(result) {
              if (result.confirm) {
                wx.openSetting();
              }
            },
          });
        }
      },
    });
  },

  onShareAppMessage() {
    return {
      title: "校车出发了...",
      path: `/pages/location/location?recordId=${this.data.recordId}`,
    };
  },

  /**
   * 开始/关闭分享
   */
  locationClick() {
    if (this.data.shareLocation) {
      this.setData({
        shareLocation: false,
      });
      this.endLocation();
    } else {
      this.setData({
        shareLocation: true,
      });
      this.startLocation();
    }
  },

  /**
   * 开始更新位置
   */
  startLocation() {
    var that = this;
    wx.showToast({
      title: "行程开始了",
    });
    this.setData({
      recordId: Date.parse(new Date()),
    });
    wx.startLocationUpdateBackground({
      success: (result) => {
        wx.onLocationChange(util.throttle(that.updateData, 500));
      },
      fail: (error) => {
        console.log("开启后台位置更新失败", error);
      },
    });
  },

  /**
   * 结束更新位置
   */
  endLocation() {
    var that = this;

    wx.stopLocationUpdate({
      success: (result) => {
        wx.showToast({
          title: "行程结束",
        });
        setTimeout(function () {
          that.updateData({
            longitude: -1,
            latitude: -1,
          });
        }, 2000);
      },
    });
  },

  /**
   * 上传数据/更新界面
   * @param {*} res
   */
  updateData(res) {
    var that = this;
    var points = this.data.info.points || [];
    if (points.length > 0) {
      var lastObj = points[points.length - 1];
      if (
        lastObj.longitude == res.longitude &&
        lastObj.latitude == res.latitude
      ) {
        return;
      }
    }
    db.collection("track")
      .add({
        data: {
          recordId: that.data.recordId,
          latitude: res.latitude,
          longitude: res.longitude,
          direction: res.direction,
          time: util.dateFormat("YYYY-mm-dd HH:MM:SS", new Date()),
        },
      })
      .then((result) => {
        console.log("上传结果", result);
      })
      .catch((error) => {
        console.error("上传失败", error);
      });
    this.drawLine(res);
  },
  /**
   * 更新界面
   */
  drawLine(res) {
    console.log("数据是", res);
    console.log("觉度是", res.direction);
    if (res.longitude == -1) return;
    var points = this.data.info.points;
    points.push({ latitude: res.latitude, longitude: res.longitude });
    this.data.info.points = points;
    this.data.info.longitude = res.longitude;
    this.data.info.latitude = res.latitude;
    this.data.markers[0]["longitude"] = res.longitude;
    this.data.markers[0]["latitude"] = res.latitude;
    if (res.direction) {
      this.data.markers[0]["rotate"] = res.direction;
    }

    this.data.info.polyline = [
      {
        points: points,
        color: "#0000FF",
        width: 10,
        arrowLine: true,
        borderWidth: 2,
        dottedLine: false,
      },
    ];
    this.setData({
      info: this.data.info,
      markers: this.data.markers,
    });
  },
  /**
   * 查看我的运动轨迹
   */
  look() {
    wx.navigateTo({
      url: `/pages/location/location?recordId=${this.data.recordId}`,
    });
  },
});
